<?php
/**
 * @title 528. 按权重随机选择 - 随机+二分
 * @author start2004
 */

// ini_set("memory_limit", "128M");

// class Solution {
//
//     function find() {
//
//     }
// }


class Solution {
    /**
     * @param Integer[] $w
     */
    function __construct($w) {
        $this->sumArray = [
            [$w[0], 0],
        ];

        /**
         * @since 2021-08-30 累计求和
         */
        for($i=1; $i<count($w); $i++){
            $this->sumArray[$i] = [$this->sumArray[$i-1][0] + $w[$i], $i];
        }
        $this->sum = current(end($this->sumArray));
    }

    /**
     * @return Integer
     */
    function pickIndex() {
        /**
         * @since 2021-08-30 随机
         */
        $r = rand(1, $this->sum);

        /**
         * @since 2021-08-30 二分查找, left < r <= right
         */
        if($r <= $this->sumArray[0][0]){
            return $this->sumArray[0][1];
        } else {
            $left = 0;
            $right = count($this->sumArray);
            while($right-$left >= 2){
                $mid = ($left+$right)>>1;
                $val = $this->sumArray[$mid][0];

                if($val >= $r){
                    $right = $mid;
                } else {
                    $left = $mid;
                }
            }

            /**
             * @return
             */
            return $this->sumArray[$right][1];
        }
    }
}

/**
 * @url http://127.0.0.1/leetcode/202108/2021.08.30.php
 */
$datas = [
    [
        ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"],
        [[[1,3]],[],[],[],[],[]],
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
// foreach ($datas as $data){
//     if(count($data) <= 20){
//         var_dump($data);
//     } else {
//         var_dump(count($data));
//     }
//
//     $obj = new Solution();
//     $result = $obj->(...$data);
//     // $result = $obj->($xhprof->tree($data));
//     // $result = $obj->($xhprof->listNode($data));
//     // $result = $obj->find(...$data);
//     var_dump($result);
//     // if(count($result)<=20){
//     //     var_dump($result);
//     // } else {
//     //     var_dump(count($result));
//     // }
//     echo str_repeat(PHP_EOL, 3);
//     echo str_repeat("<br>", 3);
// }

foreach ($datas as $data){
    $obj = new $data[0][0](...$data[1][0]);

    for ($i=1; $i<count($data[0]); $i++){
        $func = $data[0][$i];
        $param = $data[1][$i];
        $result = $obj->$func(...$param);

        echo $data[0][$i] ."(\"". implode(",", $data[1][$i]) ."\") ";
            if($result === true){
                echo "True";
            } elseif($result === false) {
                echo "False";
            } elseif($result === null) {
                echo "Null";
            } elseif(is_array($result)) {
                var_dump($result);
            } else {
                echo $result;
            }
        echo PHP_EOL;
    }

    echo str_repeat(PHP_EOL, 3);
}
$xhprof->end();
